/*
 * OCaml Support For IntelliJ Platform.
 * Copyright (C) 2010 Maxim Manuylov
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/gpl-2.0.html>.
 */

package manuylov.maxim.ocaml.run;

import com.intellij.openapi.options.ConfigurationException;
import com.intellij.openapi.options.SettingsEditor;
import org.jetbrains.annotations.NotNull;

import javax.swing.*;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;

/**
 * @author Maxim.Manuylov
 *         Date: 07.04.2010
 */
public class OCamlRunConfigurationEditor extends SettingsEditor<OCamlRunConfiguration> {
    private OCamlRunConfigurationForm myForm;

    public OCamlRunConfigurationEditor(@NotNull final OCamlRunConfiguration configuration) {
        myForm = new OCamlRunConfigurationForm(configuration);
    }

    protected void resetEditorFrom(@NotNull final OCamlRunConfiguration config) {
        copyBean(config, myForm);
    }

    protected void applyEditorTo(@NotNull final OCamlRunConfiguration config) throws ConfigurationException {
        copyBean(myForm, config);
    }

    private void copyBean(@NotNull final OCamlRunConfigurationParams source, @NotNull final OCamlRunConfigurationParams target) {
        try {
            final BeanInfo beanInfo = Introspector.getBeanInfo(OCamlRunConfigurationParams.class);
            for (final PropertyDescriptor propertyDescriptor : beanInfo.getPropertyDescriptors()) {
                final Method writeMethod = propertyDescriptor.getWriteMethod();
                final Method readMethod = propertyDescriptor.getReadMethod();
                writeMethod.invoke(target, readMethod.invoke(source));
            }        
        } catch (final Throwable e) {
            throw new RuntimeException(e);
        }
    }

    @NotNull
    protected JComponent createEditor() {
        return myForm.getRootPanel();
    }

    protected void disposeEditor() {
        myForm = null;
    }
}